#include "group.h"
#include "appl_thread.h"

#include <stdlib.h>

int GroupNum = 0;

struct GroupTable GT;

void CreateGroup(struct user* creator, const char* name)
{
    struct group* g = (struct group*)malloc(sizeof(struct group)); 
    
    g->name = name;
    g->gip = "224.12.12.12";
    g->user_num = 1;
    
    TGAP_LIST_INSERT_HEAD(&GT, g, field);

    JoinGroup(creator, g);
}

int JoinGroup(struct user* member, struct group* g)
{
    int udp_socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (udp_socket_fd < 0)
    {
        perror("creat socket fail\n");
        return -1;
    }

    //2、加入组播  组播地址224.0.0.0~239.255.255.255
    struct ip_mreq zu = {0};
    zu.imr_multiaddr.s_addr = inet_addr(g->gip); //设置组播地址
    zu.imr_interface.s_addr = inet_addr("0.0.0.0");
    int ret = setsockopt(udp_socket_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &zu, sizeof(zu));
    if (ret < 0)
    {
        perror("setsockopt fail\n");
        return -1;
    }
    else
    {
        printf("已经加入组：[%s:%s], 等待接收组消息！！！\n", g->name, member->name);
    }

    //3、设置UDP的地址并绑定
    struct sockaddr_in local_addr = {0};               //地址信息结构体
    local_addr.sin_family = AF_INET;                   //使用IPv4协议
    local_addr.sin_port = htons(g_port);                 //网络通信都使用大端格式
    local_addr.sin_addr.s_addr = inet_addr("0.0.0.0"); //32位的整形
    //注意：Linux下，加入组播后，绑定地址只能绑定0.0.0.0地址否则会接收不到数据

    ret = bind(udp_socket_fd, (struct sockaddr *)&local_addr, sizeof(local_addr));
    if (ret < 0)
    {
        
        perror("bind fail:");
        return -1;
    }

    TGAP_LIST_INSERT_HEAD(&(g->ut), member, field);

    pthread_t g_recv_thread_id;
    pthread_create(&g_recv_thread_id, NULL, Thread_Recv,   (void *)&udp_socket_fd);
    return pthread_join(g_recv_thread_id, NULL);
}



void PrintGroupTable()
{
    printf("----------Online Group----------\n");
    if(TGAP_LIST_EMPTY(&GT)){
        printf("There is no group exsited\n");
    }
    struct group* g = NULL;
    TGAP_LIST_TRAVERSE(&GT, g, field){
        printf("group name:%s gid:%s\n", g->name, g->gip);
    }
    printf("------------------------------\n");
}



